<template>
    <div class="homework-container">
        <div class="content">
            <div class="homework-title">
                <van-cell-group inset>
                    <van-field
                        v-model="homeworkInfo.title"
                        rows="1"
                        label=""
                        type="textarea"
                        placeholder="输入答案标题（必填）"
                        maxlength="50"
                        show-word-limit
                        autosize
                    />
                </van-cell-group>
            </div>
            <div class="homework-desc">
                <van-cell-group inset>
                    <van-field
                        v-model="homeworkInfo.answerContext"
                        autosize
                        label=""
                        type="textarea"
                        placeholder="输入答案详细描述"
                        maxlength="500"
                        show-word-limit
                    />
                </van-cell-group>
            </div>
            <div class="attachments">
                <div class="add-attachment">
                    <div>
                        <span class="label">添加附件</span>
                        <span class="desc">单个附件不超过100M</span>
                    </div>
                    <div class="icon-add" v-if="homeworkInfo.answerMaterialInfoList.length<3">
                        <img v-if="isApp()" class="icon-add" :src="require('@/assets/images/icon-add.png')" alt="" @click="appUpload" />
                        <uploader
                            v-else
                            :acceptSize="acceptFileSize"
                            :acceptTypes="fileTypes"
                            @on-success="onFileSuccess"
                            @on-error="onFileError"
                        >
                            <img class="icon-add" :src="require('@/assets/images/icon-add.png')" alt="" />
                        </uploader>
                    </div>
                    
                </div>
                <div class="homework-files" v-if="homeworkInfo.answerMaterialInfoList&&homeworkInfo.answerMaterialInfoList.length">
                    <div class="homework-file" v-for="(item, index) in homeworkInfo.answerMaterialInfoList" :key="item.materialId">
                        <img class="file-icon" :src="imgSrc(item.materialType)" alt="" />
                        <div class="file-info">
                            <div class="file-name">{{item.materialFullName}}</div>
                            <div class="file-size">{{item.materialSizeFormat}}</div>
                        </div>
                        <div class="file-operate">
                            <img class="icon-delete" :src="require('@/assets/images/icon-delete.png')" alt="" @click="deleFile(item, index)" />
                            <div class="upload-status" :class="{'success': item.materialStatus === 'usable', 'transcoding': item.materialStatus === 'transcoding', 'fail': item.materialStatus !== 'usable' && item.materialStatus !== 'transcoding'}">
                                {{item.materialStatus === 'usable'?'上传成功':item.materialStatus === 'transcoding' ? '上传中...' : '上传失败'}}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
        </div>
        <footer>
            <div class="submit-num" v-if="homeworkInfo.times !== -1">还可以提交{{remainingTimes}}次</div>
            <van-button v-if="homeworkInfo.times !== -1" type="primary" :loading="loading" :disabled="!remainingTimes" @click="save">提交</van-button>
            <van-button v-else type="primary" :loading="loading" @click="save">提交</van-button>
        </footer>
        <van-popup v-model:show="show" round position="bottom" safe-area-inset-bottom>
            <div class="confirm-header">
                <div class="confrim-title">
                    确认提交作业吗？
                </div>
                <div class="confirm-desc" v-if="homeworkInfo.times !== -1 && remainingTimes - 1 > 0">本次提交后，作业还可修改{{remainingTimes - 1}}次</div>
                <div class="confirm-desc" v-if="homeworkInfo.times !== -1 && remainingTimes - 1 === 0">本次提交后，作业将不可修改</div>
            </div>
            <div class="confirm-ok" @click="confirmSubmit">确认提交</div>
            <div class="confirm-cancel" @click="cancel">取消</div>
        </van-popup>
        <van-popup v-model:show="showExit" round position="bottom" safe-area-inset-bottom>
            <div class="confirm-header">
                <div class="confrim-title">
                    确认退出编辑作业吗？
                </div>
                <div class="confirm-desc">退出将不保存修改</div>
            </div>
            <div class="confirm-ok" @click="exit">确认退出</div>
            <div class="confirm-cancel" @click="cancelExit">取消</div>
        </van-popup>
    </div>
</template>

<script setup>
import { preview } from '@yanxiu/player';
import { onMounted, reactive, ref, computed } from 'vue';
import { Uploader, Button, Field, CellGroup, Icon, Popup } from 'vant';
import { useRoute, onBeforeRouteLeave } from 'vue-router';
import { useStore } from 'vuex';
import uploader from '@/components/uploader/upload-material.vue';
import { getAcceptTypes } from '@/lib/tools.js';
import {isApp} from '@/lib/judge-env.js';
import { handleErrorPage } from '@/lib/tools.js';
const route = useRoute();
const store = useStore();

let isNext = true;
const acceptTypes = ref(['jpg', 'jpeg', 'png', 'gif']);
const fileTypes = ref(getAcceptTypes(['document', 'audio', 'video', 'img']));
const acceptSize = ref(5 * 1024 * 1024);
const acceptFileSize = ref(100 * 1024 * 1024);
const loading = ref(false);
const show = ref(false)
const showExit = ref(false)
const fileTypes1 = ['audio', 'doc', 'img', 'pdf', 'ppt', 'video', 'xls', 'catalogue', 'edit', 'live', 'evaluate']
const imgs = {
    'audio': require('@/assets/images/file-icons/audio-icon.png'),
    'doc': require('@/assets/images/file-icons/doc-icon.png'),
    'img': require('@/assets/images/file-icons/img-icon.png'),
    'others': require('@/assets/images/file-icons/others-icon.png'),
    'pdf': require('@/assets/images/file-icons/pdf-icon.png'),
    'ppt': require('@/assets/images/file-icons/ppt-icon.png'),
    'video': require('@/assets/images/file-icons/video-icon.png'),
    'xls': require('@/assets/images/file-icons/xls-icon.png'),
    'catalogue': require('@/assets/images/catalogue-icon.png'),
    'edit': require('@/assets/images/file-icons/doc-icon.png'),
    'live': require('@/assets/images/file-icons/live-icon.png'),
    'evaluate': require('@/assets/images/file-icons/evaluate-icon.png'),
}
const fileList = ref([]);
let initHomework;
// 慕课详情数据
const detailData = ref({});
// 作业表单数据
const homeworkInfo = ref({
    name: '', // 作业名称
    context: '', // 作业内容
    homeWorkMaterialInfoList: [], // 作业附件
    title: '', // 作答标题
    answerContext: '', // 作答内容
    answerMaterialInfoList: [], // 作答附件
    times: 0,
    answerTimes: 0
});
function imgSrc(str) {
    return fileTypes1.indexOf(str) === -1 ? imgs.others: imgs[str]
}
// 有效剩余提交次数
const remainingTimes = computed(() => {
    let allTimes = homeworkInfo.value?.times || 0;
    let answerTimes = homeworkInfo.value?.answerTimes || 0;
    return allTimes - answerTimes
})
const brandInfo = computed(() => {
    return store.state.brand?.publishBrand;
})
const onFileSuccess = (ids, data) => {
    console.log('success data', ids, data);
    homeworkInfo.value.answerMaterialInfoList.push(...data);
    timerInterval && clearInterval(timerInterval);
    getFileStatus(homeworkInfo.value.answerMaterialInfoList);
    // materialSearch
};
const onFileError = (info) => {
    console.log('info', info)
    if (info.code === 1001) {
        G_dispatchEvent('toast', { message: info.message, type: 'error'});
    } else {
        G_dispatchEvent('toast', { message: info.desc || '上传失败', type: 'error'});
    }
};

let timerInterval = null;

const getFileStatus = () => {
    timerFn();
    timerInterval = setInterval(() => {
        timerFn();
    }, 5000);
};

const timerFn = () => {
    const fileIds = [];
    homeworkInfo.value.answerMaterialInfoList.forEach((item) => {
        if (item.materialStatus != 'usable') {
            fileIds.push(item.materialId);
        }
    });
    if (fileIds.length) {
        G_transmit('materialSearch', {
                name: 'materialSearch',
                message: false,
                data: {
                    materialIds: fileIds,
                    pageIndex: 1,
                    pageSize: 20
                }
            })
            .then(({ status, data, message }) => {
                if (status && status.code === 200) {
                    const rows = data.rows;
                    let flag = false;
                    rows.forEach((item) => {
                        homeworkInfo.value.answerMaterialInfoList.forEach((cItem, index) => {
                            if (cItem.materialId === item.materialId) {
                                homeworkInfo.value.answerMaterialInfoList.splice(index, 1, item);
                            }
                            if (cItem.materialStatus != 'usable') {
                                flag = true;
                            }
                        });
                    });
                    if (!flag) {
                        timerInterval && clearInterval(timerInterval);
                    }
                }
            })
            .catch(({ status }) => {
                if (status) {
                    G_dispatchEvent('toast', { message: status.desc, type: 'error'});
                } else {
                    G_dispatchEvent('toast', { message: '似乎出了什么状况，正在恢复中...', type: 'error'});
                }
            });
    } else {
        timerInterval && clearInterval(timerInterval);
    }
};

const onFileTip = () => {
    G_dispatchEvent('toast', { message: '最多只能上传3个文件', type: 'error'});
};

// app上传文件
const appUpload = () => {
    console.log('appupload')
    store.dispatch('jsBridge/SXYJSBridge', {
        method: 'commonJsBridge',
        fun: 'selectFile', //  上传类型 album|camera
        data: {
            type: [0, 1, 2],
            albumParams: {
                max: 3
            },
            dtBrandId:brandInfo.value.brand
        },
        callback: (data) => {
            console.log('data2', data)
            homeworkInfo.value.answerMaterialInfoList = [...homeworkInfo.value.answerMaterialInfoList, ...data.materials];
            timerInterval && clearInterval(timerInterval);
            getFileStatus(homeworkInfo.value.answerMaterialInfoList);
        }
    });
};

const deleFile = (item, index) => {
    homeworkInfo.value.answerMaterialInfoList.splice(index, 1)
}
// 获取作业详情
function getHomeworkInfo () {
    if (!route.params.homeworkId) {
        return false;
    }
    loading.value = true;
    G_transmit('homeworkInfo', {
        queries: {
            homeWorkId: route.params.homeworkId
        }
    }).then((res) => {
        homeworkInfo.value = res?.data || {};
        homeworkInfo.value.title = res?.data?.homeWorkAnswerVO?.title || '';
        homeworkInfo.value.answerContext = res?.data?.homeWorkAnswerVO?.context || '';
        homeworkInfo.value.answerMaterialInfoList = res?.data?.homeWorkAnswerVO?.answerMaterialInfoList || [];
        homeworkInfo.value.answerMaterialInfoList.forEach(item => {
            item.materialStatus = 'usable'
        })
        initHomework = {...homeworkInfo.value}
    }).finally(() => {
        loading.value = false;
    })
}
// 获取课程详情
async function getCourseDetail() {
    try {
        let res = await G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })

        detailData.value = res.data || {};

        // 不是购买者 并且不是创建人
        let notCourseUser = !detailData.value?.isBuy && !detailData.value?.isMyCreate;

        let isPublish = detailData.value?.publishState == 1 && detailData.value?.state == 4;

        // 课程未发布 除创建人和已经报名的人都不能看
        if (!isPublish && notCourseUser) {
            handleErrorPage('unpublished', route.params.moocId);
        }
        // 慕课发布了 除创建人和已经报名的人都不能看
        if(notCourseUser) {
            handleErrorPage('notsignup', route.params.moocId);
        }
        getHomeworkInfo();
    } catch(_err) {
        // 禁用课程 30800500 删除课程 30800404
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            handleErrorPage('delete', route.params.moocId);
        }  else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}
// 提交
const save = async () => {
    if (!homeworkInfo.value.title) {
        G_dispatchEvent('toast', { message: '请输入作答标题', type: 'error'});
        return;
    } else if (homeworkInfo.value.title.length > 50 || homeworkInfo.value.title.length < 2) {
        G_dispatchEvent('toast', { message: '作答标题应该在2-50个字符之内！', type: 'error'});
        return
    }
    if (homeworkInfo.value.answerContext && homeworkInfo.value.answerContext.trim()) {
        let newVal = homeworkInfo.value.answerContext.trim();
        if (newVal.length > 500 || newVal.length < 2) {
            G_dispatchEvent('toast', { message: '作答内容应该在2-500个字符之内！', type: 'error'});
            return
        }
    } else {
        if (homeworkInfo.value.answerMaterialInfoList && homeworkInfo.value.answerMaterialInfoList.length) {
        } else {
            G_dispatchEvent('toast', { message: '请输入作答内容或者上传附件，至少作答一项', type: 'error'});
            return
        }
    }
    show.value = true
};
const confirmSubmit = () => {
    isNext = false
    loading.value = true;
    let params = {
        context: homeworkInfo.value?.answerContext || '',
        homeworkAnswerId: homeworkInfo.value?.homeWorkAnswerVO?.answerId ? homeworkInfo.value?.homeWorkAnswerVO?.answerId : '', // 这个id是否为空来判断是保存还是更新，如果为空就是报保存，如果不为空就是更新
        homeworkId: route.params.homeworkId,
        materialIdList: homeworkInfo.value?.answerMaterialInfoList && homeworkInfo.value.answerMaterialInfoList.length ? homeworkInfo.value.answerMaterialInfoList.map(item => item.materialId) : [],
        moocId: route.params.moocId,
        name: homeworkInfo.value.title
    };
    console.log('params', params)
    G_transmit('homeworkAnswer', {
        data: params
    }).then(res => {
        show.value = false
        G_dispatchEvent('toast', { message: `提交成功`, type: 'success'});
        goHomework()
    }, error => {
        console.log('error', error.status.desc || '提交失败')
        G_dispatchEvent('toast', { message: error.status.desc || '提交失败', type: 'success'});
    }).finally(() => {
        loading.value = false;
    });
}
const goHomework = () => {
    store.dispatch('jsBridge/disposeBridge', {
        method: 'goNewPage',
        url: {
            name: 'homework',
            params: {
                moocId: route.params.moocId,
                homeworkId: route.params.homeworkId
            }
        },
        naviBarHidden: false
    })
}
const cancel = () => {
    show.value = false
}
const exit = () => {
    console.log('exit')
    isNext = false
    store.dispatch('jsBridge/disposeBridge', {
        isBack: true,
        data: {
            refresh: false
        }
    });
}
const cancelExit = () => {
    showExit.value = false
}
onBeforeRouteLeave((to, from, next) => {
    console.log('to', remainingTimes.value > 0 && JSON.stringify(homeworkInfo.value) != JSON.stringify(initHomework) && isNext)
    if ((homeworkInfo.value.times === -1 || (homeworkInfo.value.times !== -1&&remainingTimes.value > 0)) && JSON.stringify(homeworkInfo.value) != JSON.stringify(initHomework) && isNext) {
        setTimeout(() => {
            showExit.value = true;
        }, 10);
        next(false);
    } else {
        next();
    }
});
onMounted(() => {
    store.dispatch('jsBridge/disposeBridge', {
        method: 'setNativeTitle',
        options: {
            title: route.meta.title,
            showBack: true
        }
    });
    getCourseDetail();
    if(isApp()) {
        store.dispatch('jsBridge/SXYJSBridge', {
            method: 'commonRepeatJsBridge',
            fun: 'backSetting', //  上传类型 album|camera
            data: {
                custom: true
            },
            callback: (data) => {
                console.log('custom', data)
                if ((homeworkInfo.value.times === -1 || (homeworkInfo.value.times !== -1&&remainingTimes.value > 0)) && JSON.stringify(homeworkInfo.value) != JSON.stringify(initHomework) && isNext) {
                    setTimeout(() => {
                        showExit.value = true;
                    }, 10);
                } else {
                    store.dispatch('jsBridge/disposeBridge', {
                        isBack: true,
                        data: {
                            refresh: false
                        }
                    });
                }
            }
        });
    }
});
</script>
<style lang="scss" scoped>
.homework-container {
    min-height: 100vh;
    padding-bottom: 130px;
    background: #f5f5f5;
    display: flex;
    flex-direction: column;
    .content {
        font-family: PingFangSC-Regular, PingFang SC;
        .homework-title {
            padding: 0 15px;
            background: #ffffff;
            .van-cell-group {
                border-bottom: 1px solid #E0E2E4;
                border-radius: 0;
            }
            .van-field {
                :deep(.van-field__value) {
                    textarea::-webkit-input-placeholder{   /* 使用webkit内核的浏览器 */
                        font-size: 14px;
                        font-weight: 600;
                        color: #A2A3A4;
                    }
                    textarea:-moz-placeholder{    /* Firefox版本4-18 */
                        font-size: 14px;
                        font-weight: 600;
                        color: #A2A3A4;
                    }              
                    textarea::-moz-placeholder{    /* Firefox版本19+ */
                        font-size: 14px;
                        font-weight: 600;
                        color: #A2A3A4;
                    }              
                    textarea:-ms-input-placeholder{   /* IE浏览器 */
                        font-size: 14px;
                        font-weight: 600;
                        color: #A2A3A4;
                    }
                }
            }
        }
        .homework-desc {
            padding: 0 15px;
            background: #ffffff;
            .van-field {
                :deep(.van-field__value) textarea{
                    min-height: 190px;
                }
            }
        }
        .attachments {
            margin-top: 10px;
            background: #ffffff;
            padding: 14px 15px 14px;
            .add-attachment {
                display: flex;
                justify-content: space-between;
                align-items: center;
                .label {
                    font-size: 15px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    color: #171A1D;
                    line-height: 24px;
                }
                .desc {
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #A2A3A4;
                    line-height: 22px;
                    margin-left: 6px;
                }
                .icon-add {
                    width: 20px;
                    height: 20px;
                }
                .van-uploader :deep(.van-uploader__input-wrapper) {
                    height: 20px;
                }
            }
            .homework-files {
                margin-bottom: 6px;
            }
        }
    }
    footer {
        width: 100%;
        position: fixed;
        left: 0;
        bottom: 0;
        background: #ffffff;
        padding: 8px 15px;
        padding-bottom: calc(constant(safe-area-inset-bottom) + 15px);
        padding-bottom: calc(env(safe-area-inset-bottom) + 15px);
        box-shadow: 0px -4px 6px 0px rgba(140,149,179,0.08);
        .submit-num {
            font-size: 13px;
            font-weight: 400;
            color: #FF9201;
            line-height: 20px;
            text-align: center;
            margin: 2px 0 10px;
        }
        .van-button {
            width: 100%;
            height: 44px;
            border-radius: 4px;
            background-color: #0084F6;
            font-size: 16px;
        }
    }
}
.van-cell-group {
    margin: 0;
}
.van-field  {
    padding: 15px 0;
    :deep(.van-field__value) {
        // position: relative;
        // .van-field__body::after {
        //     // padding-right: 40px
        //     content: '';
        //     display: inline-block;
        //     width: 40px;
        // }
        .van-field__word-limit {
            // position: absolute;
            // bottom: 0;
            // right: 0;
            margin: 0;
            background: #ffffff;
            font-size: 14px;
            font-weight: 400;
            color: #A2A3A4;
            line-height: 22px;

        }
        textarea::-webkit-input-placeholder{   /* 使用webkit内核的浏览器 */
            font-size: 13px;
            font-weight: 400;
            color: #A2A3A4;
            line-height: 22px;
        }
        textarea:-moz-placeholder{    /* Firefox版本4-18 */
            font-size: 13px;
            font-weight: 400;
            color: #A2A3A4;
            line-height: 22px;
        }              
        textarea::-moz-placeholder{    /* Firefox版本19+ */
            font-size: 13px;
            font-weight: 400;
            color: #A2A3A4;
            line-height: 22px;
        }              
        textarea:-ms-input-placeholder{   /* IE浏览器 */
            font-size: 13px;
            font-weight: 400;
            color: #A2A3A4;
            line-height: 22px;
        }
    }
}
.homework-files {
    .homework-file {
        height: 84px;
        background: #F5F5F5;
        border-radius: 2px;
        display: flex;
        padding: 0 6px 0 15px;
        margin-top: 10px;
        .file-icon {
            width: 28px;
            height: 32px;
            align-self: center;
        }
        .file-info {
            width: 0;
            flex: 1;
            margin-left: 8px;
            margin-top: 16px;
            .file-name {
                font-size: 14px;
                font-weight: 400;
                color: #171A1D;
                line-height: 22px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
            .file-size {
                font-size: 12px;
                font-weight: 400;
                color: #A2A3A4;
                line-height: 18px;
                margin-top: 4px;
            }
        }
        .file-operate {
            margin-left: 4px;
            margin-top: 30px;
            text-align: right;
            .icon-delete {
                width: 14px;
                height: 14px;
                margin-right: 6px;
            }
            .upload-status {
                font-size: 10px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                line-height: 16px;
                margin-top: 12px;
                &.success {
                    color: #00B042;
                }
                &.fail {
                    color: #FD5930;
                }
                &.transcoding {
                    color: #a2a3a4;
                }
            }
        }
    }
}
:deep(.van-popup--bottom.van-popup--round) {
    border-radius: 8px 8px 0px 0px;
}
.confirm-header {
    padding: 13px 0 12px;
    border-bottom: 1px solid #EEEEEE;
    text-align: center;
    .confirm-title {
        font-size: 16px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #171A1D;
        line-height: 24px;
    }
    .confirm-desc {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #6E7074;
        margin-top: 6px;
    }
}
.confirm-ok {
    padding: 12px 0;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #171A1D;
    line-height: 24px;
    text-align: center;
}
.confirm-cancel {
    padding: 12px 0;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #171A1D;
    line-height: 24px;
    text-align: center;
    border-top: 8px solid #F5F5F5;
}
</style>
